package com.alibaba.csp.sentinel.dashboard.rule.nacos;

/**
 * packageName com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosPublisher
 *
 * @author liudonghai
 * @version JDK 11
 * @date 2025/8/22
 * @description 基类 NacosPublisher 用于提供通用的 Nacos 连接测试功能
 */
/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.alibaba.csp.sentinel.dashboard.config.NacosRuleConstants;
import com.alibaba.nacos.api.config.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * Nacos 规则发布者基类
 * 提供通用的 Nacos 连接测试功能
 */
public abstract class NacosPublisher {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    protected ConfigService configService;

    /**
     * 测试Nacos连通性和配置信息
     */
    protected void testNacosConnectivity(String appName, String postfix) {
        try {
            String dataId = appName + postfix;
            String groupId = NacosRuleConstants.GROUP_ID;
            logger.info("=== Nacos Connectivity Test ===\nApp Name: {}\n Data ID: {}\n Group ID: {}\n", appName, dataId, groupId);

            // 获取Nacos服务器信息
            // 注意：这里无法直接获取服务器地址，但可以通过异常来判断连接状态

            // 尝试获取配置（不抛出异常的方式）
            try {
                String testConfig = configService.getConfig(dataId, groupId, 1000);
                logger.info("Nacos connection: SUCCESS\nConfig exists: {}\n", (testConfig != null));
                if (testConfig != null) {
                    logger.info("Config length: {}\n", testConfig.length());
                }
            } catch (Exception e) {
                logger.info("Nacos connection test failed: {}\n", e.getMessage());
            }

            logger.info("=== End Nacos Test ===\n");

        } catch (Exception e) {
            logger.error("Nacos connectivity test error: {}\n", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 测试Nacos发布功能
     */
    public void testPublishContent(String app, String postfix, String rules) {
        try {
            String dataId = app + postfix;
            String groupId = NacosRuleConstants.GROUP_ID;

            // 将规则对象转换为字符串（假设使用JSON格式）
            logger.info("=== Nacos Publish Test ===\nApp Name: {}\nData ID: {}\nGroup ID: {}\nContent to publish: {}\n", app, dataId, groupId, rules);

            // 利用configService从nacos获取发布的内容并输出
            String existingConfig = configService.getConfig(dataId, groupId, 3000);
            logger.info("Existing config before publish: " + (existingConfig != null ? existingConfig.length() + " characters" : "null"));

            // 模拟发布配置到Nacos
            boolean published = configService.publishConfig(dataId, groupId, rules);
            logger.info("Publish result: {}\n", (published ? "SUCCESS" : "FAILED"));

            // 等待一段时间确保配置同步
            Thread.sleep(1000);

            // 如果没有获取到，调用nacos-api再获取一次发布的内容并输出
            String newConfig = configService.getConfig(dataId, groupId, 3000);
            if (newConfig != null) {
                logger.info("Retrieved config after publish: {} characters\nConfig matches:{}", newConfig.length(), newConfig.equals(rules));
            } else {
                // 再次尝试获取
                Thread.sleep(2000);
                String retryConfig = configService.getConfig(dataId, groupId, 3000);
                logger.info("Failed to retrieve config after publish\nRetry config retrieval: " + (retryConfig != null ? retryConfig.length() + " characters" : "null"));
            }

            logger.info("=== End Nacos Publish Test ===");

        } catch (Exception e) {
            logger.error("Nacos publish test error: {}", e.getMessage());
            e.printStackTrace();
        }
    }
}
